package com.example.common.support;

import com.example.function.sys.model.one.SysLogger;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * <h1>响应前处理器</h1>
 * 在后置拦截器执行前执行
 * Created by hanqf on 2021/7/22 17:57.
 */

@Component
@ControllerAdvice(annotations = {RestController.class})
@Slf4j
public class CP_ResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Value("${operate.log.open}")
    private boolean operate_log_open;

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(operate_log_open && body instanceof AjaxResponse) {
            if (request instanceof ServletServerHttpRequest) {
                HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
                SysLogger sysLogger = (SysLogger) servletRequest.getAttribute(CP_OperateLogInterceptor.LOGGER_ENTITY);
                try {
                    sysLogger.setLogReturnData(objectMapper.writeValueAsString(body));
                    servletRequest.setAttribute(CP_OperateLogInterceptor.LOGGER_ENTITY,sysLogger);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

            }
        }
        return body;
    }
}
